import React, {Component} from 'react';
import {Text, View, StyleSheet, Button} from 'react-native';
import * as ActionTypes from '../actions/types';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center'
  },

  counterTipText: {
    marginBottom: 10
  },

  counterText: {
    backgroundColor: 'red'
  },

  counterInfo: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: 'pink',
    maxHeight: 70,
    minWidth: 200
  },

  counterContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'skyblue',
  }
});

export default class CounterComponent extends Component {
  constructor(props) {
    super(props)
  }

  componentDidMount() {
    let {store} = this.context;
    this.unSubscribe = store.subscribe(
      () => {
        this.forceUpdate();
      }
    );
  }

  componentWillUnmount() {
    this.unSubscribe();
  }

  _onAddClicked() {
    let {store} = this.context;

    store.dispatch({
      type: ActionTypes.ADD_NUM
    });
  }

  _onDecClicked() {
    let {store} = this.context;

    store.dispatch({
      type: ActionTypes.DEC_NUM
    });
  }

  render() {
    let {store} = this.context;
    const {num}= store.getState();

    return (
      <View style={styles.container}>
        <View style={styles.counterInfo}>
          <Text style={styles.counterTipText}>Current count is:</Text>
          <View style={styles.counterContainer}>
            <Button
              title=" - "
              color="#841584"
              onPress={this._onDecClicked.bind(this)}
            />
            <Text style={styles.counterText}> {num} </Text>
            <Button
              title=" + "
              color="#841584"
              onPress={this._onAddClicked.bind(this)}/>
          </View>
        </View>
      </View>
    );
  }
}

CounterComponent.contextTypes = {
  store: React.PropTypes.object
}